<?php

namespace app\controller\home;

use app\BaseController;
use app\validate\User;
use Firebase\JWT\JWT;
use think\App;
use think\exception\ValidateException;
use think\facade\Cache;
use think\facade\Log;
use think\facade\Validate;
use think\Request;
use app\model\User as userModel;

class Login extends BaseController
{


    /**
     * 登录
     * @param Request $request
     * @param userModel $userModel
     * @return \think\response\Json|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index(Request $request, userModel $userModel)
    {
        $data = $request->param();
        try {
            validate(User::class)->check($data);

        } catch (ValidateException $e) {
            $msg = $e->getMessage();
            return result(RESULT_FAILED, '', $msg);
        }


        if ($user_id = $userModel->checkPassword($data['mobile'],md5($data['password']) )) {
            $info['token'] = $this->createJwt($user_id);
            return result(RESULT_SUCCESS, $info);
        }
        return result(RESULT_SUCCESS, '', '账号或密码错误');
    }

    /**
     * 用户注册
     * @param Request $request
     * @param userModel $userModel
     * @return \think\response\Json|void
     */
    public function register(Request $request, userModel $userModel)
    {
        $data = $request->param();
        try {
            validate(User::class)->check($data);

        } catch (ValidateException $e) {
            $msg = $e->getMessage();
            return result(RESULT_FAILED, '', $msg);
        }

        $cache_code = Cache::get($data['mobile'],'');
        if (empty($data['code']) || $cache_code!=$data['code']){
            return result(RESULT_FAILED, '','验证码错误');
        }
        Cache::delete($data['mobile']);
        if ($userModel->add($data['mobile'], $data['password'])) {
            return result(RESULT_SUCCESS, '注册成功');
        }
    }


    /**
     * 模拟发送手机验证码
     * @param Request $request
     * @return \think\response\Json
     */
    public function createMobileCode(Request $request){
        $data = $request->param();
        $validate = Validate::rule('mobile', 'require|mobile');
        if (!$validate->check($data)) {
            return result(RESULT_FAILED,'',$validate->getError());
        }
        $code = rand(1000,9999);
        Cache::set($data['mobile'], $code, 600);//将验证码存入缓存中
        return result(RESULT_SUCCESS, $code);
    }
    /**
     * 生成token
     * @param $userId
     * @return string
     */
    private function createJwt($userId)
    {
        $key = md5('gaojian'); //jwt的签发密钥
        $time = time(); //签发时间
        $expire = $time + 14400; //过期时间
        $token = array(
            "user_id" => $userId,
            "iss" => "gaojian",//签发组织
            "aud" => "gaojian", //签发作者
            "iat" => $time,
            "nbf" => $time,
            "exp" => $expire
        );
        $jwt = JWT::encode($token, $key);
        return $jwt;
    }
}
